package hero.nio;

import java.nio.charset.Charset;
import java.nio.CharBuffer;
import java.nio.ByteBuffer;
import java.io.FileInputStream;
import java.nio.channels.FileChannel;
/* from java2s */

public class NioFileTest {

    public static void main(String[] args){
        echoFile("test.txt");
    }

    public static void echoFile(String filePath) {
        Charset charset = Charset.forName("UTF-8");
        FileInputStream in;
        FileChannel channel;
        long fileSize;
        ByteBuffer buf;
        try {
            in = new FileInputStream(filePath);
            channel = in.getChannel();
            fileSize = channel.size();
            buf = ByteBuffer.allocate((int)fileSize);
            channel.read(buf);
            buf.rewind();
            System.out.println(charset.decode(buf));
            channel.close();
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void convertByteBufferToCharBuffer() {
        ByteBuffer bb = ByteBuffer.wrap(new byte[] { 'e','b','c','0',0,1,2,3,'b','e','f'});
        bb.rewind();
        CharBuffer cb = bb.asCharBuffer();
        System.out.println("shit");
        while (cb.hasRemaining()) {
            System.out.println(cb.position() + "->" + cb.get());
        }
    }

    public static void testFlip()  {
        CharBuffer cb = CharBuffer.allocate(30);
        cb.put("shit happend 混蛋");
        println(cb);

        cb.flip();
        println(cb);

        cb.put("what");
        cb.flip();
        println(cb);
    }


    public static void println(CharBuffer cb) {
        System.out.print("pos=" + cb.position() + ",limit=" + cb.limit()+": ");
        while (cb.hasRemaining()) {
            System.out.print(cb.get());
        }
        System.out.println();
    }

}
